package com.fy.common.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
public class I18nHelper {
    private static Logger logger = LoggerFactory.getLogger(I18nHelper.class);


    private static ResourceBundleMessageSource resourceBundleMessageSource;

    @Autowired
    public void setResourceBundleMessageSource(ResourceBundleMessageSource resourceBundleMessageSource) {
        this.resourceBundleMessageSource = resourceBundleMessageSource;
    }

    public static String getMessage(String msgKey, Object[] args) {
        return resourceBundleMessageSource.getMessage(msgKey, args, LocaleContextHolder.getLocale());
    }

    public static String getMessage(String msgKey) {
        Locale locale = LocaleContextHolder.getLocale();
        try {
            msgKey = resourceBundleMessageSource.getMessage(msgKey, null, locale);
        }catch (Exception e){
            logger.info("getMessage error:",e);
        }
        return msgKey;
    }


    @Bean
    public ResourceBundleMessageSource getResourceBundleMessageSource () {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setUseCodeAsDefaultMessage(true);
        source.setCacheSeconds(10);
        source.setBasename("resourceBundleMessageSource");
        source.setDefaultEncoding("utf-8");
        return source;
    }


}
